// ============ AI工具调度系统 - 核心 Store ============

import { defineStore } from 'pinia';
import { ref, reactive, computed } from 'vue';
import Ajv, { type ValidateFunction } from 'ajv';
import addFormats from 'ajv-formats';
import type { 
  ToolDefinition, 
  ToolExecutionRequest, 
  ToolExecutionResult, 
  ToolExecutionTask,
  ToolQueryFilter,
  ToolExecutionContext
} from './types';
import { 
  stableStringify, 
  combineSignals, 
  createTimeoutSignal, 
  Semaphore,
  generateCacheKey
} from './utils';

// ============ 内部工具 ============
const AJV_INSTANCE = addFormats(new Ajv({ allErrors: true }));

// ============ Core Store Implementation ============
export const useAiToolsStore = defineStore('aiTools', () => {
  // 状态
  const tools = reactive<Map<string, ToolDefinition>>(new Map());
  const validatorCache = reactive<Map<string, ValidateFunction>>(new Map());
  const executionQueue = ref<ToolExecutionTask[]>([]);
  const resultCache = reactive<Map<string, { result: any; timestamp: number }>>(new Map());
  
  // 配置
  const maxConcurrency = ref(3);
  const cacheTimeout = ref(5 * 60 * 1000); // 5分钟
  const defaultTimeout = ref(30 * 1000); // 30秒
  
  // 控制器
  const semaphore = new Semaphore(maxConcurrency.value);
  
  // 计算属性
  const registeredTools = computed(() => Array.from(tools.values()));
  const runningTasks = computed(() => executionQueue.value.filter(t => t.status === 'running'));
  const queuedTasks = computed(() => executionQueue.value.filter(t => t.status === 'pending'));
  
  // ============ 工具注册管理 ============
  
  /**
   * 注册工具
   */
  function registerTool(definition: ToolDefinition): void {
    if (!definition.id || !definition.name || !definition.handler) {
      throw new Error('Tool definition must include id, name, and handler');
    }
    
    tools.set(definition.id, { ...definition });
    
    // 预编译参数校验器
    if (definition.parameters) {
      const validator = AJV_INSTANCE.compile(definition.parameters);
      validatorCache.set(definition.id, validator);
    }
  }
  
  /**
   * 批量注册工具
   */
  function registerTools(definitions: ToolDefinition[]): void {
    definitions.forEach(registerTool);
  }
  
  /**
   * 注销工具
   */
  function unregisterTool(toolId: string): boolean {
    const removed = tools.delete(toolId);
    validatorCache.delete(toolId);
    return removed;
  }
  
  /**
   * 获取工具定义
   */
  function getTool(toolId: string): ToolDefinition | undefined {
    return tools.get(toolId);
  }
  
  /**
   * 查询工具（支持按分类、标签、名称过滤）
   */
  function queryTools(filter?: ToolQueryFilter): ToolDefinition[] {
    let result = registeredTools.value;
    
    if (filter) {
      if (filter.category) {
        result = result.filter(t => t.metadata?.category === filter.category);
      }
      if (filter.tags && filter.tags.length > 0) {
        result = result.filter(t => 
          filter.tags!.some(tag => t.metadata?.tags?.includes(tag))
        );
      }
      if (filter.name) {
        const namePattern = new RegExp(filter.name, 'i');
        result = result.filter(t => 
          namePattern.test(t.name) || namePattern.test(t.id)
        );
      }
    }
    
    return result;
  }
  
  // ============ 工具执行 ============
  
  /**
   * 执行工具
   */
  async function executeTool(request: ToolExecutionRequest): Promise<ToolExecutionResult> {
    const { toolId, parameters, metadata } = request;
    const startTime = Date.now();
    const taskId = `${toolId}-${startTime}-${Math.random().toString(36).slice(2)}`;
    
    // 获取工具定义
    const toolDef = getTool(toolId);
    if (!toolDef) {
      return {
        success: false,
        error: `Tool '${toolId}' not found`,
        errorType: 'error',
        metadata: { executionTime: 0 }
      };
    }
    
    // 创建执行任务
    const task: ToolExecutionTask = {
      id: taskId,
      toolId,
      parameters: parameters || {},
      status: 'pending',
      startTime,
      abortController: new AbortController()
    };
    
    executionQueue.value.push(task);
    
    try {
      // 参数校验
      if (toolDef.parameters) {
        const validator = validatorCache.get(toolId);
        if (validator && !validator(parameters)) {
          const errors = validator.errors?.map(err => 
            `${err.instancePath || 'root'} ${err.message}`
          ).join(', ') || 'Invalid parameters';
          
          return {
            success: false,
            error: `Parameter validation failed: ${errors}`,
            errorType: 'error',
            metadata: { executionTime: Date.now() - startTime }
          };
        }
      }
      
      // 检查缓存
      const cacheKey = generateCacheKey(toolId, parameters || {});
      const cached = resultCache.get(cacheKey);
      if (cached && (Date.now() - cached.timestamp) < cacheTimeout.value) {
        return {
          success: true,
          data: cached.result,
          metadata: { 
            executionTime: Date.now() - startTime,
            fromCache: true 
          }
        };
      }
      
      // 获取信号量
      await semaphore.acquire();
      
      try {
        task.status = 'running';
        
        // 构建执行上下文
        const timeout = metadata?.timeout || toolDef.metadata?.timeout || defaultTimeout.value;
        const signals = [
          task.abortController?.signal,
          metadata?.signal,
          createTimeoutSignal(timeout)
        ].filter(Boolean);
        
        const combinedSignal = combineSignals(signals);
        const context: ToolExecutionContext = { signal: combinedSignal };
        
        // 执行工具
        const result = await toolDef.handler(parameters || {}, context);
        
        // 缓存结果（仅成功的结果）
        resultCache.set(cacheKey, { result, timestamp: Date.now() });
        
        task.status = 'completed';
        task.endTime = Date.now();
        task.result = {
          success: true,
          data: result,
          metadata: { executionTime: task.endTime - startTime }
        };
        
        return task.result;
        
      } catch (error: any) {
        // 错误分类
        let errorType: 'cancelled' | 'timeout' | 'error' = 'error';
        let errorMessage = String(error?.message || error);
        
        if (error?.name === 'AbortError' || /abort/i.test(errorMessage)) {
          if (/timeout/i.test(errorMessage)) {
            errorType = 'timeout';
            errorMessage = 'Tool execution timed out';
          } else {
            errorType = 'cancelled';
            errorMessage = 'Tool execution was cancelled';
          }
        }
        
        task.status = 'error';
        task.endTime = Date.now();
        task.result = {
          success: false,
          error: errorMessage,
          errorType,
          metadata: { executionTime: task.endTime - startTime }
        };
        
        return task.result;
        
      } finally {
        semaphore.release();
      }
      
    } catch (error: any) {
      // 外层错误处理（不应该发生）
      task.status = 'error';
      task.endTime = Date.now();
      
      return {
        success: false,
        error: `Unexpected error: ${error?.message || error}`,
        errorType: 'error',
        metadata: { executionTime: task.endTime! - startTime }
      };
    } finally {
      // 清理任务（保留最近100个）
      if (executionQueue.value.length > 100) {
        executionQueue.value = executionQueue.value.slice(-100);
      }
    }
  }
  
  /**
   * 取消工具执行
   */
  function cancelExecution(taskId: string): boolean {
    const task = executionQueue.value.find(t => t.id === taskId);
    if (!task || task.status === 'completed' || task.status === 'cancelled') {
      return false;
    }
    
    task.abortController?.abort();
    task.status = 'cancelled';
    return true;
  }
  
  /**
   * 清空缓存
   */
  function clearCache(): void {
    resultCache.clear();
  }
  
  /**
   * 更新并发限制
   */
  function setConcurrencyLimit(limit: number): void {
    if (limit < 1) throw new Error('Concurrency limit must be at least 1');
    maxConcurrency.value = limit;
    // 注意：这里不重新创建 semaphore，因为可能影响正在运行的任务
  }
  
  // ============ 暴露 Store API ============
  return {
    // 状态
    registeredTools,
    runningTasks,
    queuedTasks,
    maxConcurrency,
    cacheTimeout,
    defaultTimeout,
    
    // 工具管理
    registerTool,
    registerTools,
    unregisterTool,
    getTool,
    queryTools,
    
    // 执行
    executeTool,
    cancelExecution,
    
    // 配置
    clearCache,
    setConcurrencyLimit,
  };
});

// 重新导出核心类型和工具函数
export { 
  orchestrateToolCalls, 
  executeToolCall, 
  executeToolCallsRound 
} from './orchestrator';
export type { 
  ToolDefinition, 
  ToolExecutionRequest, 
  ToolExecutionResult,
  OrchestrationOptions,
  OrchestrationResult 
} from './types';